<?php
class Application_Model_Foto extends Zend_Db_Table_Abstract{
    protected $_name = 'fotos';

    protected $_referenceMap = array(
        'Galeria' => array(
            'columns'       => 'galeria_id',
            'refTableClass' => 'Application_Model_Galeria',
            'refColumns'    => 'id'
        )
    );

    public function getById($id){
        $select = $this->select()
            ->where("status = 'A' AND id = ?", $id);

        $result = $this->fetchAll($select);
        $arrEvento = $result->toArray();
        return $arrEvento;
    }

    public function getByGaleria($galeria_id){
        $select = $this->select()
            ->where("status = 'A' AND galeria_id = ?", $galeria_id);

        $result = $this->fetchAll($select);
        $arrFotos = $result->toArray();
        return $arrFotos;
    }

    public function uploadFoto($file){
        $server_dir = $_SERVER["DOCUMENT_ROOT"];
        $foto_dir = $server_dir."/galerias/";

        if(file_exists($foto_dir) && is_writable($foto_dir)){
            if( ( ($file["type"] == "image/gif")
                || ($file["type"] == "image/jpeg")
                || ($file["type"] == "image/pjpeg")
                || ($file["type"] == "image/png") )
                && ($file["size"] < 2000000) ){
                $destination = $foto_dir.$file["name"];

                if(move_uploaded_file($file["tmp_name"], $destination)){
                    return $file["name"];
                }else{
                    error_log("[FOTO_ERROR]".$file['error']." ".$file["name"]);
                    return 0;
                }
            }else{
                error_log("[FOTO_ERROR]no es imagen valida");
                return false;
            }
        }else{
            error_log("[FOTO_ERROR] dir not writable or does not exist");
            return false;
        }
    }

    public function addFoto($nombre, $galeria_id, $description, $status){
        $row = $this->createRow();

        $row->nombre = $nombre;
        $row->galeria_id = $galeria_id;
        $row->description = $description;
        $row->status = $status;

        $row->save();

        $id = $this->_db->lastInsertId();

        return $id;
    }
}